package com.junglone.fang.controller;

import com.alibaba.fastjson.JSONObject;
import com.junglone.fang.websocket.WebSocketServer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Description:
 *
 * @author junglone: <a href="mailto:cjlnzb@hotmail.com">cjlnzb@hotmail.com</a>
 * @version 1.0.0
 * @since 2019/08/15 10:41
 */
@RestController
@RequestMapping("/checkcenter")
public class CheckCenterController {

    /**
     * Description: 页面请求
     *
     * @author junglone: <a href="mailto:cjlnzb@hotmail.com">cjlnzb@hotmail.com</a>
     * @since 2019/08/15 10:43
     */
    @CrossOrigin
    @PostMapping("/socket/{cid}")
    public String socket(@PathVariable String cid, HttpServletRequest servletRequest) {
        String strId = servletRequest.getParameter("sid");

        System.out.println("cid = " + cid + " ---- strId = " + strId);

        // 加入匹配队列
        WebSocketServer.joinPairing(strId);

        // 3 秒后开始匹配
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            System.err.println("InterruptedException ==== " + e.getMessage());
        }

        long lStartTime = System.currentTimeMillis();
        // System.out.println("lStartTime = " + lStartTime);

        JSONObject jsonObject = new JSONObject();

        // 匹配到的同时也在请求匹配的人的 id
        String strPairedId;
        while (true) {
            strPairedId = WebSocketServer.getPaired(strId);
            System.out.println("strPairedId = " + strPairedId);

            if (null != strPairedId) {
                break;
            }

            // 匹配时间超过 20 秒依然没人, 直接返回匹配不到提示
            long lEndTime = System.currentTimeMillis();
            // System.out.println("lEndTime = " + lEndTime);
            // System.out.println("lEndTime - lStartTime = " + (lEndTime - lStartTime));

            boolean bBreak = lEndTime - lStartTime >= 20000;
            if (bBreak) {
                jsonObject.put("data", "latter");
                return jsonObject.toJSONString();
            }
        }

        jsonObject.put("data", strPairedId);

        return jsonObject.toJSONString();
        // return "sssss";
    }

    /**
     * Description: 推送数据接口
     *
     * @param cid     cid
     * @param message message
     *
     * @return ApiReturnObject
     *
     * @author junglone: <a href="mailto:cjlnzb@hotmail.com">cjlnzb@hotmail.com</a>
     * @since 2019/08/15 10:44
     */
    @RequestMapping("/socket/push/{cid}")
    public String pushToWeb(@PathVariable String cid, String message) {
        try {
            WebSocketServer.sendInfo(message, cid);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return "success";
    }
}